﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using xTeam.Glgcx.CommonUtilities;
using System.IO;

namespace xTeam.Glgcx.Controllers.Manage
{
    public class ArchiveController : BaseController
    {

        //
        // GET: /Archive/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult List(string key = "", int pageIndex = 1, int classifyId = 0)
        {
            int totalRows = 0;
            int pageSize = 20;
            ArchiveViewModel viewModel = new ArchiveViewModel();
            viewModel.ClassifyList = _classifyBal.GetClassiyfListByModuleKey("Archive");
            viewModel.ArchiveList = _archiveBal.ArchiveList(key, pageIndex, pageSize, classifyId, null, ref totalRows);
            ViewData["Pager"] = this.CreatePager(Url.Action("List", new { key = key, pageIndex = "{0}", classifyId = classifyId }), totalRows, pageSize, pageIndex);

            ViewData.Model = viewModel;
            return View();
        }
        #region 文字新闻
        public ActionResult Edit(int newsId = 0)
        {
            ArchiveViewModel viewModel = new ArchiveViewModel();
            viewModel.ClassifyList = _classifyBal.GetClassiyfListByModuleKey("Archive");
            var archive = _archiveBal.GetArchiveById(newsId, null);
            archive = archive ?? new ENews() { AddDateTime = DateTime.Now, Isvalid = true };
            viewModel.Archive = archive;
            ViewData.Model = viewModel;

            return View();
        }
        /// <summary>
        /// 添加修改新闻
        /// </summary>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(ENews news)
        {
            if (news.ClassifyId < 1)
                throw new HttpException("请选择分类");
            int ret = _archiveBal.Update(news);
            return RedirectToAction("Edit", new { newsId = ret });
        }
        /// <summary>
        /// 删除新闻
        /// </summary>
        [HttpPost]
        public ActionResult Delete(int newsId)
        {
            // 执行新闻删除
            int ret = _archiveBal.Delete(newsId);
            return new EmptyResult();
        }
        #endregion

        #region 图片新闻
        public ActionResult Album(int newsId = 0)
        {
            ArchiveViewModel viewModel = new ArchiveViewModel();
            var archive = _archiveBal.GetArchiveById(newsId, null);
            archive = archive ?? new ENews() { AddDateTime = DateTime.Now, Isvalid = true };
            viewModel.Archive = archive;
            ViewData.Model = viewModel;
            ViewData["ImageRoot"] = _imageRoot;
            return View();
        }
        /// <summary>
        /// 保存图片基础信息信息
        /// </summary>
        [HttpPost]
        public ActionResult Album(
            string imageName = ""
            , string filePath = ""
            , int imageId = 0
            , bool isCover = false
            , int fkId = 0)
        {

            imageName = string.IsNullOrEmpty(imageName) ? Path.GetFileName(filePath) : imageName;
            imageName = Server.UrlDecode(imageName);
            string sourceFileName = Server.MapPath(Server.UrlDecode(filePath));
            string destDirectory = string.Format("{0}/{1}", _imageRoot, fkId);
            string destFileName = Server.MapPath(string.Format("{0}/{1}", destDirectory, imageName));

            if (System.IO.File.Exists(sourceFileName))
            {
                try
                {
                    //检查文件夹
                    if (!System.IO.Directory.Exists(Server.MapPath(destDirectory)))
                        System.IO.Directory.CreateDirectory(Server.MapPath(destDirectory));
                    // 移动图片
                    System.IO.File.Copy(sourceFileName, destFileName, true);

                    int result = _archiveBal.SaveImage(new EAlbum()
                    {
                        ImageId = (int)imageId,
                        ImageName = imageName.Trim(),
                        IsCover = (bool)isCover,
                        NewsId = fkId,
                    });
                }
                catch
                {
                }
            }

            return new EmptyResult();
        }
        /// <summary>
        /// 设置封面
        /// </summary>
        [HttpPost]
        public ActionResult SetCover(int imageId = 0)
        {
            int result = _archiveBal.SetCover(imageId);
            return new EmptyResult();
        }
        /// <summary>
        /// 保存图片扩展信息
        /// </summary>
        public ActionResult AlbumItemPost()
        {
            if (Request.Form["ImageId"] != null)
            {
                string[] ids = Request.Form.GetValues("ImageId");
                string[] ss = Request.Form.GetValues("Sequence");
                string[] ts = Request.Form.GetValues("tbTitle");
                string[] des = Request.Form.GetValues("Description");
                int imageId, sequence;
                for (int i = 0; i < ids.Length; i++)
                {
                    int.TryParse(ids[i], out imageId);
                    int.TryParse(ss[i], out sequence);
                    _archiveBal.SaveImage(imageId, ts[i], des[i], sequence);
                }
            }
            return new EmptyResult();
        }
        /// <summary>
        /// 从图片扩展中删除图片
        /// </summary>
        [HttpPost]
        public ActionResult DeleteImageItem()
        {
            if (Request.Form["ImageId"] != null)
            {
                string[] ids = Request.Form.GetValues("ImageId");
                List<EAlbum> imageList = _archiveBal.DeleteImage(ids);
                //删除图片
                foreach (var item in imageList)
                {
                    try
                    {
                        string fileDirectory = Server.MapPath(string.Format("{0}/{1}", _imageRoot, item.NewsId));
                        System.IO.File.Delete(string.Format("{0}/{1}", fileDirectory, item.ImageName));
                        // System.IO.File.Delete(string.Format("{0}/s_{1}", fileDirectory, item.ImageName));
                    }
                    catch (Exception e)
                    {
                    }
                }
            }
            return new EmptyResult();
        }


        #endregion

    }
}
